use crate::common::utils::http_utils::{error_json, success_json, success_json_data};
use crate::common::utils::parse_utils::parse_multi;
use crate::common::utils::sign_utils::{rsa_sign, HashType};
use crate::service::model::chat_handler_model::{ClientMessage, PostBean};
use crate::service::model::store::{RegisterPost, SendGst};
use crate::service::routes::websocket::CHAT_RTC;
use crate::service::server::chat::ChatServer;
use crate::sql;
use crate::sql::store::{is_continue_user, login_sql, register_sql, set_login_token_sql};
use actix::Addr;
use actix_multipart::Multipart;
use actix_web::http::header::{DispositionParam, HttpDate};
use actix_web::*;
use chrono::Local;
use futures::StreamExt;
use rand::Rng;
use sqlx::{Pool, Postgres};

#[get("/store/home")]
pub async fn home() -> Result<HttpResponse, Error> {
    Ok(HttpResponse::Ok().body(sql::store::get_home()))
}
#[get("/store/info/{id}")]
pub async fn info(
    _req: HttpRequest,
    pool: web::Data<Pool<Postgres>>,
) -> Result<HttpResponse, Error> {
    let pool = pool.get_ref();
    let id = _req.match_info().get("id").unwrap();

    println!("id:{}", id);
    let data = sql::store::get_info(pool, String::from(id)).await.unwrap();

    println!("data:{:?}", data);
    Ok(HttpResponse::Ok().body(success_json_data(data)))
}

#[get("/store/goods/{id}")]
pub async fn goods(
    _req: HttpRequest,
    // _srv:web::Data<Pool<Postgres>>
) -> Result<HttpResponse, Error> {
    Ok(HttpResponse::Ok().body(sql::store::get_goods_json()))
}

#[get("/store/shop/{id}")]
pub async fn shop() -> Result<HttpResponse, Error> {
    let result = sql::store::get_shop().await;
    Ok(HttpResponse::Ok().body(result))
}

#[post("/send/gst")]
pub async fn gst(
    mut body: web::Json<SendGst>,
    senv: web::Data<Addr<ChatServer>>,
) -> Result<HttpResponse, Error> {
    let mut value_mold: usize;
    let mut value: String;
    if body.types == "ice" {
        value_mold = 112;
        value = format!(
            "{{\"data\":\"{0}\",\"index\":{1}}}",
            body.content, body.index
        );
    } else {
        value_mold = 111;
        value = format!("{0}{1}", body.index, body.content);
    }
    let post_bean = PostBean {
        mold: CHAT_RTC.parse().unwrap(),
        id: body.send_id,
        value_mold,
        value,
        json: serde_json::Value::String("".to_string()),
    };
    let msg = ClientMessage {
        id: body.receive_id,
        msg: serde_json::to_string(&post_bean).unwrap(),
    };
    senv.do_send(msg);
    println!("gst:{:?}", body);
    // while let Some( field) = body.next().await{
    //     field.unwrap().content_disposition().unwrap()
    // }
    Ok(HttpResponse::Ok().body("{\"status\":200}"))
}
#[post("/store/login")]
pub async fn login(
    mut body: Multipart,
    pool: web::Data<Pool<Postgres>>,
) -> Result<HttpResponse, Error> {
    let para = parse_multi(body).await.unwrap();
    let pool = pool.as_ref();

    let login_model = login_sql(
        pool,
        para.get("phone").unwrap().to_string(),
        para.get("pwd").unwrap().to_string(),
    )
    .await;

    return if login_model.is_ok() {
        let mut login_model = login_model.unwrap();
        let mut now = Local::now().timestamp().to_string();
        now.push_str(&login_model.id.to_string());

        let token = rsa_sign(&now.to_string(), HashType::Sha256);
        let result = set_login_token_sql(
            pool,
            para.get("phone").unwrap(),
            para.get("pwd").unwrap(),
            &token,
        )
        .await;

        if result.is_ok() {
            login_model.token = token;
            Ok(HttpResponse::Ok().body(success_json_data(login_model)))
        } else {
            Ok(HttpResponse::Ok().body(error_json(501, "登录失败")))
        }
    } else {
        println!("error:{:?}", login_model.err().unwrap());
        Ok(HttpResponse::Ok().body(error_json(501, "账号密码不匹配")))
    };
}

#[post("/store/register")]
pub async fn register(
    mut body: Multipart,
    pool: web::Data<Pool<Postgres>>,
    pics: web::Data<Vec<String>>,
) -> Result<HttpResponse, Error> {
    let result = parse_multi(body).await.unwrap();
    let pool = pool.get_ref();
    let pics = pics.get_ref();
    let mut rng = rand::thread_rng();
    let pic_index = rng.gen_range(0, pics.len());
    let pic = pics.get(pic_index).unwrap().to_string();
    let phone = result.get("phone").unwrap().to_string();
    let nick = result.get("nick").unwrap().to_string();
    let pwd = result.get("pwd").unwrap().to_string();
    let is_continue = is_continue_user(pool, phone.clone()).await.unwrap();
    if is_continue > 0 {
        return Ok(HttpResponse::Ok().body(error_json(501, "手机好已经注册")));
    }

    let result = register_sql(pool, phone, pwd, nick, pic).await.unwrap();

    if result > 0 {
        Ok(HttpResponse::Ok().body(success_json()))
    } else {
        Ok(HttpResponse::Ok().body(error_json(501, "注册失败")))
    }
}
